<template>
  <el-header height="60px" class="nav-bar">
    <div class="logo">学习空间@HuLuSpace</div>
    <div class="spacer"></div>
    <div class="actions">
      <template v-if="userStore.user">
        <el-dropdown>
          <span class="el-dropdown-link">
            {{ userStore.user }} ({{ getRoleName(userStore.currentRole) }})
            <el-icon><arrow-down /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="goToHome">首页</el-dropdown-item>
              <el-dropdown-item @click="goToProfile">个人中心</el-dropdown-item>
              <el-dropdown-item divided disabled>切换角色</el-dropdown-item>
              <el-dropdown-item 
                  v-for="role in userStore.roles" 
                  :key="role" 
                  @click="confirmSwitchRole(role)"
              >
                {{ getRoleName(role) }}
              </el-dropdown-item>
              <el-dropdown-item divided @click="handleLogout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-dialog
          title="确认切换角色"
          v-model = "dialogVisible"
          width="30%"
        >
          <span>确定要切换到角色 "{{ pendingRoleName }}" 吗？</span>
          <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="switchRole">确认</el-button>
          </template>
        </el-dialog>
      </template>
      <template v-else>
        <el-button class="nav-btn" text @click="openLogin">登录</el-button>
        <el-button class="nav-btn" text @click="openRegister">注册</el-button>
      </template>
    </div>
    <LoginDialog v-model="loginVisible" @login-success="onLoginSuccess" />
    <RegisterDialog v-model="registerVisible" />
  </el-header>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import LoginDialog from '@/components/LoginDialog.vue'
import RegisterDialog from '@/components/RegisterDialog.vue'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const router = useRouter()
const loginVisible = ref(false)
const registerVisible = ref(false)
const dialogVisible = ref(false)
const pendingRole = ref(null)

const openLogin = () => loginVisible.value = true
const openRegister = () => registerVisible.value = true
const goToProfile = () => router.push('/profile')
const goToHome = () => router.push('/')

const pendingRoleName = computed(() => (pendingRole.value ? getRoleName(pendingRole.value) : ''))


const roleNameMap = {
  ROLE_ADMIN: '管理员',
  ROLE_TEACHER: '教师',
  ROLE_STUDENT: '学生'
}

function getRoleName(role) {
  return roleNameMap[role] || role // 如果找不到对应，默认显示原始字符串
}

const handleLogout = async () => {
  try {
    await userStore.logout()
    ElMessage.success('已退出登录')
  } catch (e) {
    ElMessage.error('退出登录失败，请重试')
  }
}

const onLoginSuccess = (userInfo) => {
  userStore.loginSuccess(userInfo)
  goToHome()
}

// 点击角色项时触发，弹出确认对话框
function confirmSwitchRole(role) {
  console.log(role)
  pendingRole.value = role
  dialogVisible.value = true
}

// 点击确认切换
function switchRole() {
  if (!pendingRole.value) return
  userStore.currentRole = pendingRole.value
  dialogVisible.value = false
  console.log('已切换角色:', pendingRole.value)
  // TODO: 如果需要，调用接口刷新权限、通知页面刷新等
}

onMounted(() => {
  try {
    const userData = userStore.checkLoginStatus()
    // 登录状态有效，userData可用
  } catch (err) {
    // 登录失效，执行登出等操作
    userStore.logout()
    goToHome()
  }
})
</script>

<style scoped>
.nav-bar {
  position: fixed;         /* 固定在视口顶部 */
  top: 0;                  /* 顶部距离为 0 */
  left: 0;                 /* 左边距为 0，确保从最左开始 */
  width: 100vw;            /* 宽度为整个视口宽度 */
  z-index: 1000;           /* 确保层级高，避免被其他内容覆盖 */
  display: flex;
  align-items: center;
  background-color: #1890ff;
  color: white;
  padding: 0 20px;
  font-family: Arial, sans-serif;
  height: 60px;            /* 可选，设置固定高度 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 可选，阴影美化 */
}

.logo {
  font-size: 20px;
  font-weight: bold;
}

.spacer {
  flex: 1;
}

.actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.el-dropdown-link {
  cursor: pointer;
  color: white;
  font-weight: 500;
  font-size: 15px;
}

.nav-btn {
  font-size: 14px;
  font-weight: 500;
  color: white;
  padding: 6px 12px;
  border-radius: 4px;
  transition: background-color 0.2s ease;
}

.nav-btn:hover {
  background-color: rgba(255, 255, 255, 0.1);
}
</style>
